package com.syni.mdd.sjb.community.base.handler;

import com.syni.mdd.sjb.common.component.utils.common.constants.CommonResultCode;
import com.syni.mdd.sjb.common.component.utils.common.constants.CommonResultMsg;
import com.syni.mdd.sjb.common.component.utils.common.entity.Error;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.sjb.common.component.utils.common.exception.SystemErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.HashMap;
import java.util.Map;

/**
 * @className GlobalExceptionHandler
 * @description TOO
 * @Author cfx
 * @DATE 2019/7/19 23:28
 * @VERSION 1.0
 **/
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(SystemErrorException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public @ResponseBody
    Error global(SystemErrorException s){
        Error error = new Error(CommonResultCode.CODE_ERROR, CommonResultMsg.HAND_FAIL);
        return error;
    }

    /**
     * 处理所有接口数据验证异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Map<String, Object> handleMethodArgumentNotValidException(
            MethodArgumentNotValidException e) {
        Map<String, Object> result = new HashMap<>();
        for (FieldError fieldError : e.getBindingResult().getFieldErrors()) {
            result = ResultMapHelper.result(CommonResultCode.CODE_ERROR_03,fieldError.getField() + " " + fieldError.getDefaultMessage());
            break;
        }
        return result;
    }

}
